//
//  UnusualAlertView.m
//  rrqs
//
//  Created by mac book on 2019/3/11.
//

#import "UnusualAlertView.h"
#import "HBHUDTool.h"

///alertView  宽
#define AlertW 280
#define AlertH 400

///各个栏目之间的距离
#define XLSpace 10
#define Space 20



@interface UnusualAlertView()<UITextViewDelegate>
//弹窗
@property (nonatomic,retain) UIView *alertView;

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;

//title
@property (nonatomic,retain) UILabel *titleLbl;
//确认按钮
@property (nonatomic,retain) UIButton *sureBtn;

@property (nonatomic,retain) UITextView *textView;

@property (nonatomic,retain) UIView *buttonView;

// 选中标签数组(数字)
@property (nonatomic, strong) NSMutableArray *selectedMarkArray;
// 选中标签数组(文字字符串)
@property (nonatomic, strong) NSMutableArray *selectedMarkStrArray;


@end


@implementation UnusualAlertView


- (instancetype)initUnusualAlertWithData:(NSArray *)dataArray{
    
    
    if (self == [super init]) {
        
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.7];
        
        
        self.dataArray = [NSMutableArray arrayWithArray:dataArray];
       
        
        
        
        self.alertView = [[UIView alloc] init];
        self.alertView.backgroundColor = [UIColor whiteColor];
        self.alertView.frame = CGRectMake(0, 0, AlertW, AlertH);
        self.alertView.layer.cornerRadius = 5.0;
        self.alertView.layer.position = self.center;
        self.alertView.userInteractionEnabled = YES;
        
        
        self.titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, AlertW, 60)];
        self.titleLbl.numberOfLines = 0;
        self.titleLbl.text = @"请选择（填入）异常原因";
        self.titleLbl.textAlignment = NSTextAlignmentCenter;
        self.titleLbl.font = DEF_FontSize_16;
        [self.alertView addSubview:self.titleLbl];
        
        
        UIButton *off_btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [off_btn setImage:[UIImage imageNamed:@"icon_shanchu"] forState:(UIControlStateNormal)];
        [self.alertView addSubview:off_btn];
        off_btn.adjustsImageWhenHighlighted = NO;
        [off_btn addTarget:self action:@selector(singleTapAction) forControlEvents:(UIControlEventTouchUpInside)];
        [off_btn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.equalTo(self.alertView).offset(-20);
            make.size.mas_equalTo(CGSizeMake(35, 35));
//            make.right.equalTo(self.alertView).offset(20);
            make.top.right.equalTo(self.alertView);

        }];
        
        

        
        float text_w = AlertW - 40;
        float text_h = 100;

        _textView = [[UITextView alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(self.titleLbl.frame), text_w, text_h)]; //初始化大小并自动释放
        _textView.textColor = [UIColor grayColor];//设置字体颜色
        _textView.layer.borderWidth = 0.8;
        _textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _textView.layer.cornerRadius = 5;
        _textView.layer.masksToBounds = YES;
        _textView.font = DEF_FontSize_14;//设置 字体 和 大小
        _textView.delegate = self;// 设置控制器为 textView 的代理方法
        _textView.backgroundColor = [UIColor whiteColor];//设置它的背景颜色
        _textView.scrollEnabled = YES;//是否可以拖动
        [self.alertView addSubview:_textView];

        
        UILabel *placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, CGRectGetWidth(self.textView.frame), 25)];
        placeHolderLabel.text = @"请输入异常原因";
        placeHolderLabel.textColor = [UIColor lightGrayColor];
        placeHolderLabel.font = DEF_FontSize_13;
        [self.textView addSubview:placeHolderLabel];
        [self.textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
        
        
        
        
         self.buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textView.frame), AlertW, 50)];
        [self.alertView addSubview:self.buttonView];

        CGFloat btnview_h = 0;
        
        CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
        CGFloat h = Space;//用来控制button距离父视图的高
        for (int i =0; i < self.dataArray.count; i++) {
            NSDictionary *dataDic = [self.dataArray objectAtIndex:i];
    
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.layer.cornerRadius= 5;
            button.layer.masksToBounds =YES;
            button.layer.borderWidth = 0.8;
            button.layer.borderColor = [UIColor lightGrayColor].CGColor;
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];

            button.titleLabel.font = DEF_FontSize_13;
            button.tag = i;
            [button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];

            
            //获取字号
            NSDictionary *attributes = @{NSFontAttributeName:DEF_FontSize_13};
            CGFloat length = [dataDic[@"mark_value"] boundingRectWithSize:CGSizeMake(self.alertView.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
            //为button赋值
            [button setTitle:dataDic[@"mark_value"] forState:UIControlStateNormal];
            //设置button的frame
            button.frame = CGRectMake(10 + w, h, length + 15 , 25);
            //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
            if(10 + w + length + 15 > self.alertView.frame.size.width){
                w = 0; //换行时将w置为0
                h = h + button.frame.size.height + 10;//距离父视图也变化
                button.frame = CGRectMake(10 + w, h, length + 15, 25);//重设button的frame
            }
            w = button.frame.size.width + button.frame.origin.x;
            if (i == self.dataArray.count-1) {
                btnview_h = CGRectGetMaxY(button.frame);
            }
            [self.buttonView addSubview:button];
            
        }
        
        self.buttonView.frame = CGRectMake(self.buttonView.frame.origin.x, self.buttonView.frame.origin.y, self.buttonView.frame.size.width, btnview_h+Space);
        
        
        float btn_h = 40;
        
        self.sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.sureBtn.frame = CGRectMake(CGRectGetMinX(self.textView.frame), CGRectGetMaxY(self.buttonView.frame), CGRectGetWidth(self.textView.frame), btn_h);
        [self.sureBtn setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
        [self.sureBtn setTitle:@"确定上报" forState:UIControlStateNormal];
        self.sureBtn.titleLabel.font = DEF_FontSize_15;
        [self.sureBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        self.sureBtn.adjustsImageWhenHighlighted = NO;
        self.sureBtn.layer.cornerRadius = 5;
        self.sureBtn.layer.masksToBounds = YES;
        self.sureBtn.backgroundColor = getColor(@"f5964f");
        [self.alertView addSubview:self.sureBtn];

        
        
        //计算高度
        CGFloat alertHeight = CGRectGetMaxY(self.sureBtn.frame)+Space ;
        self.alertView.frame = CGRectMake(0, 0, AlertW, alertHeight);
        self.alertView.layer.position = self.center;
        [self addSubview:self.alertView];
    
    }
    
    return self;
    
}

//点击二级子菜单事件
- (void)handleClick:(UIButton *)btn{
    
    NSLog(@"点击了%ld",btn.tag);
    NSDictionary *dataDic = [self.dataArray objectAtIndex:btn.tag];

    btn.selected = !btn.selected;

    if (btn.selected) {
        
        btn.layer.borderColor = getColor(@"f5964f").CGColor;
        [btn setTitleColor:getColor(@"f5964f") forState:UIControlStateNormal];
        
        [self.selectedMarkArray addObject:dataDic[@"mark_id"]];
        [self.selectedMarkStrArray addObject:btn.titleLabel.text];
        
    }else{
        
        btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        [self.selectedMarkArray removeObject:dataDic[@"mark_id"]];
        [self.selectedMarkStrArray removeObject:btn.titleLabel.text];
        
    }
    
    
    
}


- (void)buttonEvent:(UIButton *)sender
{
    
    if (self.textView.text.length == 0 && self.selectedMarkArray.count == 0) {

        [HBHUDTool showMessageCenter:@"请选择或填入异常原因"];
        
        return;
        
    }
    
    NSString *numStr = [self.selectedMarkArray componentsJoinedByString:@","];
    // 按钮文字字符串
    NSString *str = [self.selectedMarkStrArray componentsJoinedByString:@","];

    
    // 测试:拼接请求参数
    NSLog(@"按钮数字标识字符串:%@", numStr);
    NSLog(@"按钮文字字符串:%@", str);
    
    if (self.unusualHandleBlock) {
        self.unusualHandleBlock(self.textView.text, numStr);
    }
    
    [self singleTapAction];
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    if([text isEqualToString:@"\n"]){
        
        [textView resignFirstResponder];
        
        return NO;
    }
    
    
    return YES;
    
}


#pragma mark - 弹出 -
- (void)showAlertView
{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    [self creatShowAnimation];
}

- (void)creatShowAnimation
{
    self.alertView.layer.position = self.center;
    self.alertView.transform = CGAffineTransformMakeScale(0.90, 0.90);
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alertView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
    }];
    
}

//点击事件
-(void)singleTapAction
{
    if (self.alertView.subviews.count>0) {
        for (UIView *subs in self.alertView.subviews) {
            [subs removeFromSuperview];
        }
    }
    
    //具体的实现
    [self removeFromSuperview];
}

- (NSMutableArray *)selectedMarkArray {
    if (!_selectedMarkArray) {
        _selectedMarkArray = [NSMutableArray array];
    }
    return _selectedMarkArray;
}
- (NSMutableArray *)selectedMarkStrArray {
    if (!_selectedMarkStrArray) {
        _selectedMarkStrArray = [NSMutableArray array];
    }
    return _selectedMarkStrArray;
    
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
